package com.project.search.controller;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.search.DocSearcher;
import com.project.search.model.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
public class DocSearcherController {

    static class Response {
        // 表示搜索结果的总数量
        public int total;

        // 搜索结果集
        public List<Result> results;
    }

    private static DocSearcher searcher = new DocSearcher();

    // 借助 Jackson库 来将搜索结果序列化
    private ObjectMapper objectMapper = new ObjectMapper();

    @RequestMapping(value = "/searcher")
    public String search(@RequestParam("query") String query) throws JsonProcessingException {
        // 参数是查询词, 返回值是响应内容
        // 注意: @RequestParam 知识点

        Response response = new Response();
        response.results = searcher.search(query);
        response.total = response.results.size();

        // 将搜索结果序列化
        return objectMapper.writeValueAsString(response);
    }

}
